// client/main.go
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"trpc.group/trpc-go/trpc-go"
	"trpc.group/trpc-go/trpc-go/client"

	pb "trpc-polaris-demo/proto"
)

func main() {
	// 初始化trpc框架
	trpc.SetGlobalConfig(&trpc.Config{})

	// 创建客户端连接
	opts := []client.Option{
		client.WithTarget("polaris://HelloService"), // 使用Polaris服务发现
		client.WithTimeout(time.Second * 5),
	}

	// 创建服务客户端
	helloClient := pb.NewHelloServiceClientProxy(conn)

	log.Println("Client started, calling remote services...")

	// 测试SayHello方法
	testSayHello(helloClient)

	// 测试GetUserInfo方法
	testGetUserInfo(helloClient)

	// 持续测试，模拟真实场景
	runContinuousTest(helloClient)
}

// testSayHello 测试SayHello方法
func testSayHello(client pb.HelloServiceClientProxy) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()

	req := &pb.HelloRequest{
		Name:    "测试用户",
		Message: "这是一条测试消息",
	}

	log.Printf("Calling SayHello with: %+v", req)

	resp, err := client.SayHello(ctx, req)
	if err != nil {
		log.Printf("SayHello failed: %v", err)
		return
	}

	log.Printf("SayHello response: %s (timestamp: %d)", resp.Reply, resp.Timestamp)
}

// testGetUserInfo 测试GetUserInfo方法
func testGetUserInfo(client pb.HelloServiceClientProxy) {
	userIds := []int64{1, 2, 999} // 测试不同的用户ID

	for _, userId := range userIds {
		ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)

		req := &pb.UserRequest{
			UserId: userId,
		}

		log.Printf("Calling GetUserInfo with user_id: %d", userId)

		resp, err := client.GetUserInfo(ctx, req)
		if err != nil {
			log.Printf("GetUserInfo failed for user %d: %v", userId, err)
			cancel()
			continue
		}

		log.Printf("GetUserInfo response: ID=%d, Name=%s, Email=%s",
			resp.UserId, resp.Username, resp.Email)

		cancel()
	}
}

// runContinuousTest 持续测试，模拟真实场景
func runContinuousTest(client pb.HelloServiceClientProxy) {
	log.Println("Starting continuous test (press Ctrl+C to stop)...")

	ticker := time.NewTicker(10 * time.Second)
	defer ticker.Stop()

	counter := 0

	for {
		select {
		case <-ticker.C:
			counter++

			// 交替调用不同的方法
			if counter%2 == 0 {
				ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)

				req := &pb.HelloRequest{
					Name:    fmt.Sprintf("用户%d", counter),
					Message: fmt.Sprintf("第%d次调用", counter),
				}

				resp, err := client.SayHello(ctx, req)
				if err != nil {
					log.Printf("Continuous test SayHello failed: %v", err)
				} else {
					log.Printf("Continuous test SayHello success: %s", resp.Reply)
				}

				cancel()
			} else {
				ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)

				req := &pb.UserRequest{
					UserId: int64(counter%3 + 1), // 循环使用用户ID 1, 2, 3
				}

				resp, err := client.GetUserInfo(ctx, req)
				if err != nil {
					log.Printf("Continuous test GetUserInfo failed: %v", err)
				} else {
					log.Printf("Continuous test GetUserInfo success: %s", resp.Username)
				}

				cancel()
			}
		}
	}
}
